package com.gr.config.factory;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: MqttMessageFactory
 * Description: 工厂-策略调用 对应的信息消费
 *
 * @author binbin_hao
 * @date 2023/7/17 11:39
 */
@Component
@Slf4j
public class MqttMessageFactory implements InitializingBean, ApplicationContextAware {

    private static final Map<String, MqttMessageHandlerStrategy> mqttStrategies = new HashMap<>();
    private ApplicationContext appContext;
    @Override
    public void afterPropertiesSet() throws Exception {
        appContext.getBeansOfType(MqttMessageHandlerStrategy.class).values()
                .forEach(mqttMessageHandlerStrategy -> mqttStrategies.put(mqttMessageHandlerStrategy.getTopic(),mqttMessageHandlerStrategy));

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        appContext = applicationContext;
    }
    public static MqttMessageHandlerStrategy getMqttMessageHandler(String mqttTopic) {
        if (StringUtils.isEmpty(mqttTopic)) {
            throw new IllegalArgumentException("MqttTopic is empty.");
        }
        log.info("mqttTopicEnum:"+mqttTopic);
        String topic=null;
        if (mqttStrategies.keySet().stream().filter(mqttTopic1 ->
                MqttTopic.isMatched(mqttTopic1,mqttTopic)).findAny().isPresent()){
            topic= mqttStrategies.keySet().stream().filter(mqttTopicEnum1 ->
                    MqttTopic.isMatched(mqttTopicEnum1,mqttTopic)
            ).findFirst().get();
        }
        if (topic==null) {
            log.warn("MqttTopic not supported.topic,查不到主题对应处理类：{}"+mqttTopic);
            return null;
            // throw new IllegalArgumentException("MqttTopic not supported.");
        }
        return mqttStrategies.get(topic);
    }


}
